package com.project.petLossSystem.controller.admin;

import cn.hutool.captcha.ShearCaptcha;
import com.project.petLossSystem.common.Constants;
import com.project.petLossSystem.service.ContactItemService;
import com.project.petLossSystem.service.PetPostService;
import com.project.petLossSystem.service.UserService;
import com.project.petLossSystem.util.Result;
import com.project.petLossSystem.util.ResultGenerator;
import com.project.petLossSystem.po.Admin;
import com.project.petLossSystem.service.AdminService;
import com.project.petLossSystem.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private PetPostService petPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private ContactItemService contactItemService;

    @GetMapping("/login")
    public String login() {
        return "/pc/admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("loginId") String loginId,
                        @RequestParam("loginPassword") String loginPassword,
                        @RequestParam("verifyCode") String verifyCode,
                        HttpSession session,
                        Model model) {
        if (!StringUtils.hasText(verifyCode)) {
            model.addAttribute("errorMsg", "验证码不能为空！");
            return "/pc/admin/login";
        }
        if (!StringUtils.hasText(loginId) || !StringUtils.hasText(loginPassword)) {
            model.addAttribute("errorMsg", "账号或密码不能为空！");
            return "/pc/admin/login";
        }
        ShearCaptcha shearCaptcha = (ShearCaptcha) session.getAttribute(Constants.VERIFY_CODE_KEY);
        session.removeAttribute(Constants.VERIFY_CODE_KEY);
        if(shearCaptcha==null || !shearCaptcha.verify(verifyCode)){
            model.addAttribute("errorMsg", "验证码错误");
            return "/pc/admin/login";
        }

        Admin admin = adminService.login(loginId, loginPassword);
        if (admin != null) {
            session.setAttribute("admin", admin);
            // 超时时间
            session.setMaxInactiveInterval(Constants.ADMIN_SESSION_EXPIRE);
            return "redirect:/admin/index";
        } else {
            model.addAttribute("errorMsg", "账号或密码错误！");
            return "/pc/admin/login";
        }
    }

    @GetMapping({"", "/", "/index", "/index.html"})
    public String index(Model model) {
        // 帖子数量
        model.addAttribute("lostPost", petPostService.getPostCountToday((byte) 0));
        model.addAttribute("foundPost", petPostService.getPostCountToday((byte) 1));
        // 用户
        model.addAttribute("user", userService.getUserCountToday());
        // 联系
        model.addAttribute("contactItem", contactItemService.getItemCountToday());
        /* JVM */
        Runtime runtime = Runtime.getRuntime();
        // cpu
        model.addAttribute("cpu", runtime.availableProcessors());
        // 内存
        model.addAttribute("totalMemory", convertToGB(runtime.totalMemory()));
        model.addAttribute("freeMemory", convertToGB(runtime.freeMemory()));
        return "/pc/admin/index";
    }

    // 转gb保留两位小数
    public String convertToGB(long bytes) {
        return String.format("%.2f", bytes / (1024.0 * 1024.0 * 1024.0));
    }

    // 管理员信息页面
    @GetMapping("/profile")
    public String profile() {
        return "/pc/admin/profile";
    }

    // 密码修改
    @PutMapping("/profile/password")
    @ResponseBody
    public Result updatePassword(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword, HttpSession session) {
        if (!StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            return ResultGenerator.failureResult("参数不能为空！");
        }
        Admin admin = (Admin) session.getAttribute("admin");
        if (!admin.getLoginPassword().equals(MD5Util.MD5Encode(oldPassword, "UTF-8"))) {
            return ResultGenerator.failureResult("密码错误！");
        }
        if (adminService.updatePasswordById(admin.getAdminId(), newPassword)) {
            session.removeAttribute("admin");
            return ResultGenerator.successResult();
        }
        return ResultGenerator.failureResult("修改失败！");
    }

    // 账号和昵称修改
    @PutMapping("/profile/loginIdAndName")
    @ResponseBody
    public Result updateLoginIdAndName(@RequestParam("loginId") String loginId, @RequestParam("adminName") String adminName, HttpSession session) {
        if (!StringUtils.hasText(loginId) || !StringUtils.hasText(adminName)) {
            return ResultGenerator.failureResult("参数不能为空！");
        }
        Admin admin = (Admin) session.getAttribute("admin");
        if (adminService.updateLoginIdAndNameById(admin.getAdminId(), loginId, adminName)) {
            // 更新session信息
            admin.setLoginId(loginId);
            admin.setAdminName(adminName);
            return ResultGenerator.successResult();
        }
        return ResultGenerator.failureResult("修改失败！");
    }

    // 登出
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("admin");
        return "/pc/admin/login";
    }

}
